<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {cloneDeep} from "lodash";
import {addSysConfig, getSysConfig, updateSysConfig} from "@/api/system/config";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  id: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  remark: '',
})
const rules = reactive({
  configName: [{required: true, message: '请输入参数名称', trigger: 'blur'}],
  configKey: [{required: true, message: '请输入参数键名', trigger: 'blur'}],
  configValue: [{required: true, message: '请输入参数值', trigger: 'blur'}]
})
const formType = ref('create')


const open = async (id, type = 'create') => {
  formType.value = type;
  resetForm();
  if (type === 'create') {
  } else {
    const {data} = await getSysConfig(id);
    formData.value = {
      ...data
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  await formRef.value.validate();
  let data = cloneDeep(formData.value);
  if (data.id === undefined) {
    await addSysConfig(data);
    proxy.$modal.okNotify('新增成功');
  } else {
    await updateSysConfig(data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    id: undefined,
    configName: '',
    configKey: '',
    configValue: '',
    remark: '',
  }
}

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'create' ? '新建' : '编辑'}参数`" modalWidth="500px"
               @submit="handleSubmit">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="参数名称" prop="configName">
        <el-input v-model="formData.configName" placeholder="请输入参数名称"/>
      </el-form-item>
      <el-form-item label="参数键名" prop="configKey">
        <el-input v-model="formData.configKey" placeholder="请输入参数键名"/>
      </el-form-item>
      <el-form-item label="参数值" prop="configValue">
        <el-input v-model="formData.configValue" placeholder="请输入参数值"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
